from flask import Blueprint, request
from utilsapp.mysql_con import db_pagelist, db_fetchone, db_delete, db_update,db_insert ,db_fetchall,db_list
from utilsapp.common import assign_value, parsing_data_id,get_operate
import json
bluePrint = Blueprint('algtest', __name__)
tableName = 'algtest'


# 分页查询
@bluePrint.route('/getlist', methods=["post"])
def table_list():
    a = request.json
    sql=f'''SELECT a.*,mg.name as model_name,mg.value FROM algtest a
LEFT JOIN model_group mg on mg.id = a.models'''
    page = assign_value(a,'page')
    size = assign_value(a,'size',20)
    query = " where 1 = 1  "
    
    sql+=query
    return db_pagelist(sql,page,size)



@bluePrint.route('/add', methods=["post"])
def add():
    return db_insert(tableName,request.json)




# 删除
@bluePrint.route('/delete', methods=["post"])
def table_delete():
    id = request.json['id']
    return db_delete(tableName, f'WHERE id=%s', {'id': id})



@bluePrint.route('/edit', methods=["post"])
def a232():
    id_ = assign_value(request.json, "id")
    keys_not_add = ['id', 'model_name','value']
    addModel = {key: request.json[key]
                    for key in request.json if key not in keys_not_add}
    return db_update(tableName,addModel,f"where id =%s", {"id_": id_})
    


@bluePrint.route('/result/getlist', methods=["post"])
def table_lis1t():
    a = request.json
    id_ = assign_value(a,"id")
    start_time = assign_value(a,"start_time")
    end_time = assign_value(a,"end_time")
    model_map =  assign_value(a,"model_map")
    modelcode = assign_value(a,"modelcode")
    sql=f'''SELECT a.id,a.name,a.maker,t.model_name,t.create_time,t.modelcode,t.model_map ,t.pred_value,t.message,t.fileName,t.fileContent
from algtest a 
LEFT JOIN test_result t on a.id  = t.test_id
'''
    query = 'where 1 = 1 '
    if id_!="":
        query+=f' and a.id = {id_} '
    if model_map !="":
        query+= f" and model_map like'%{model_map}%' "
    if modelcode !="":
        query += f" and modelcode like'%{modelcode}%' "

    if start_time!="":
        query += f" and t.create_time > '{start_time}'"
    if end_time!="":
        query += f" and t.create_time < '{end_time}'"
    page = assign_value(a,'page')
    size = assign_value(a,'size',20)
    sql = sql + query
    return db_pagelist(sql,page,size)

